<template>
  <div>
    <div class="bg" :style="{ background: 'url(' + article.cover + ')' }">
      <div class="con">
        <div class="title">
          {{ article.title }}
        </div>
        <div class="bottom">
          <i class="iconfont icon-jiezhiriqi"></i>发布于<span>
            {{ dateFormat(article.createTime, "yyyy-mm-dd") }}</span
          >
          | <i class="iconfont icon-gengxinriqi"></i>更新于<span>
            {{ dateFormat(article.updateTime, "yyyy-mm-dd") }}</span
          >
          | <i class="iconfont icon-zishutongji"></i>字数统计<span>
            {{ article.words }}</span
          >
          |
          <i class="iconfont icon-shengshangyinqingicon_huaban1fuben6"></i
          >阅读时长<span> {{ article.readTime }}</span>
        </div>
      </div>
    </div>
    <div class="container">
      <el-row
        :gutter="10"
        style="margin-left: 0px; margin-right: 0px"
        type="flex"
        justify="center"
      >
        <el-col
          :span="18"
          :lg="{ span: 18 }"
          :md="{ span: 18 }"
          :sm="24"
          :xs="24"
        >
          <!-- 文章区域 -->

          <el-card class="big-padding no-top card">
            <article class="typo">
              <!-- 文章主体区域 -->
              <div
                class="txt js-toc-content article-main"
                v-html="article.content"
              ></div>
              <!-- 分割线 -->
              <el-divider></el-divider>
              <!-- 标签 -->
              <div>
                <router-link
                  v-for="(item, i) in article.tags"
                  :key="i"
                  :to="'/tag?tag=' + item.id"
                  class="txt label"
                  ># <span>{{ item.name }}</span></router-link
                >
              </div>
            </article>
            <!-- 评论区域 -->
            <el-card class="comment card">
              <div slot="header">
                <span class="txt">评论</span>
                <el-button
                  style="float: right; padding: 3px 0"
                  type="text"
                  @click="comment()"
                  >去评论</el-button
                >
              </div>
              <!-- 评论区域 -->
                <comment :comments="content" @reply="reply"></comment>
              <el-pagination
                background
                layout="prev, pager, next"
                :total="total"
                :page-size="7"
                @current-change="handleCurrentChange"
                :current-page="page"
                :hide-on-single-page="isshow"
              >
              </el-pagination>
            </el-card>
          </el-card>
        </el-col>
        <!-- 目录及最新文章 -->
        <el-col :span="6" class="hidden-sm-and-down">
          <div class="rbox">
            <el-card style="padding: 10px" v-if="value">
              <div class="title">
                <i class="iconfont icon-hanbaobao"></i> 目录
              </div>
              <div class="js-toc"></div>
            </el-card>
            <el-card class="new">
              <div class="title">
                <i class="iconfont icon-shijian"></i> 最新文章
              </div>
              <router-link
                class="item"
                :to="'/article/'+item.id"
                v-for="(item,i) in news"
                :key="i"
              >
                <div class="cover">
                  <img
                    :src="item.cover"
                    alt=""
                  />
                </div>
                <div class="right">
                  <div class="name">{{item.title}}</div>
                  <div class="time">{{timeago.format(item.createTime, 'zh_CN')}}</div>
                </div>
              </router-link>
            </el-card>
          </div>
        </el-col>
      </el-row>
      <el-dialog title="评论" :visible.sync="dialogVisible" @close="leave">
        <!-- 发表评论 -->
        <div class="clearfix">
          <el-form :model="addForm" :rules="rules" ref="addForm">
            <el-form-item prop="content">
              <el-input
                type="textarea"
                placeholder="请输入评论内容"
                maxlength="50"
                show-word-limit
                :rows="5"
                v-model="addForm.content"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="username">
              <el-input
                placeholder="请输入昵称"
                prefix-icon="el-icon-user-solid"
                v-model="addForm.username"
              >
              </el-input
            ></el-form-item>
          </el-form>
        </div>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postData">发 布</el-button>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import tocbot from "tocbot";
import dateFormat from "dateformat";
import * as timeago from "timeago.js";
import comment from './components/comment.vue'
import { getArticle, getComment, record, sendComments } from "@/api";
import flatten from "@/utils/flatten";
export default {
  components:{comment},
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的邮箱"));
    };
    return {
      news:[],
      pid: 0,
      aid: "",
      flag: 0,
      id: this.$route.params.id,
      dialogVisible: false,
      article: {},
      value: true,
      page: 1,
      total: 0,
      content: [],
      timeago,
      complete: true,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 1,
            max: 6,
            message: "长度在 1 到 6 个字符",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "请输入评论", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "长度在 1 到 50 个字符",
            trigger: "blur",
          },
        ]
      },
      addForm: {
        username: "",
        content: "",
      },

    };
  },
  methods: {
    inittocbot() {
      tocbot.init({
        // 构建目录的容器
        tocSelector: ".js-toc",
        // 文章容器
        contentSelector: ".js-toc-content",
        // 需要解析的标题
        headingSelector: "h1, h2, h3,h4,h5,h6",
        linkClass: "toc-link",
        activeLinkClass: "is-active-link",
      });
    },
    async getContentData() {
      if (!this.complete) {
        return;
      }
      this.complete = false;
      const  data  = await getComment(this.aid, {page: this.page })
      for (let i = 0; i < data.list.length; i++){
        let arr = []
        flatten(data.list[i],arr)
        data.list[i].children=arr
      }
      this.content = [...this.content,...data.list]
      console.log(this.content);
      this.total = data.total;
      this.complete = true;
    },
    comment() {
      this.flag = 0;
      this.dialogVisible = true;
    },
    reply(pid) {
      this.pid = pid;
      this.dialogVisible = true;
    },
    dateFormat,
    handleCurrentChange(newsize) {
      this.page = newsize;
      this.getContentData();
    },
    postData() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          try {
            await sendComments({
              articleId:this.aid,
              PersonId:this.pid,
              content:this.addForm.content,
              username:this.addForm.username
            })
            this.$message.success("评论成功")
            this.getContentData()
            this.$socket.emit("CommentChange");
          }catch (e){
            return this.$message.error("评论失败")
          }finally
          {
            this.dialogVisible = false;
            this.pid=0;
          }
        }
      });
    },
    leave() {
      this.$refs.addForm.resetFields();
    },
    async getnew(){
      var data = await getArticle({page:1,pagesize:6});
       this.news = data.list
      console.log(this.news);
    },
    async getdata(){
      var { data } = await this.axios.get("/article/" + this.$route.params.id);
       this.article = data.data;
        document.title = this.article.title
    }
  },
  computed: {
    isshow() {
      return this.total < 7;
    },
  },
   mounted() {
     this.aid = this.$route.params.id;
     record(this.aid);
    this.getnew()
     this.getContentData();
    tocbot.refresh();
    this.$socket.on("CommentChange",()=>{
      this.getContentData()
    })
    this.$nextTick(function () {
      this.inittocbot(); //调用需要执行的方法
      if (document.getElementsByClassName("toc-list").length === 0) {
        this.value = false;
      }
    });
  },
  created(){
    this.getdata()
  },
  beforeDestroy() {
    this.$socket.off("CommentChange");
    tocbot.destroy();
  }
};
</script>
<style scoped lang="scss">
.bg {
  padding-top: 40px;
  background-position: center !important;
  background-size: cover !important;
  background-repeat: no-repeat !important;
  width: 100vw;
  height: 50vh;
  position: relative;
  color: #fff;
  &::after {
    display: block;
    position: absolute;
    content: "";
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1;
  }
  .con {
    z-index: 10;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width: 100%;
    height: 100%;
    .title {
      font-size: 24px;
    }
  }
}
.panel-left {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}
.el-divider__text {
  background-color: var(--theme_divider) !important;
  color: var(--theme_txt) !important;
}
.label {
  margin: 0 5px;
}
.comment {
  margin-top: 10px;
}

.blue {
  color: #0097fb;
}
.cyan {
  color: rgb(4, 252, 235);
}
.article-main {
  margin-top: 10px;
}

.rbox {
  // width: 100%;
  // height: 100%;
  position: sticky;
  top: 70px;
}
.new {
  display: block;
  margin-top: 10px;
  padding: 10px;
  .title {
    margin-bottom: 10px;
  }
  .item {
    display: flex;
    margin-bottom: 10px;
    .cover {
      overflow: hidden;
      width: 60px;
      height: 60px;
      img {
        width: 60px;
        height: 60px;
        object-fit: cover;
        object-position: center;
      }
      margin-right: 10px;
    }
    .right {
      display: flex;
      width: calc(100% - 60px);
      justify-content: center;
      flex-direction: column;
      color: #666 !important;
      .time {
        font-size: 8px;
      }
    }
  }
}
@media screen and (min-width: 1200px) {
  .container {
    margin: auto;
    max-width: 1150px !important;
  }
}
@media screen and (max-width:768px){
 ::v-deep .el-dialog {
    width: 80% ;
  }
}

.el-message {
  z-index: 99999 !important;
}
</style>
<style>


.is-active-link {
  color: #fff !important;
}
.is-active-li {
  background-color: #78c8ff !important;
  border-left: 2px solid #3dacf6;
}
.toc-list-item {
  padding-left: 5px;
}
.toc-link {
  color: #666261;
}
</style>
